# websocket
from geventwebsocket.server import WSGIServer  # 我要WSGI为我提供服务
from geventwebsocket.handler import WebSocketHandler  # WSGI 遇到 WS协议的时候，处理方式
from geventwebsocket.websocket import WebSocket  # 语法提示

# 基于 Flask + geventwebsocket

from flask import Flask, request, render_template

app = Flask(__name__)

user_socket_list = []


@app.route("/ws")
def my_ws_func():
    # print(dir(request.environ))
    user_socket = request.environ.get("wsgi.websocket")  # type:WebSocket
    user_socket_list.append(user_socket)
    # web + socket
    print(user_socket)
    while 1:
        msg = user_socket.receive()  # 等待接收客户端发送过来的消息
        for us in user_socket_list:
            if us == user_socket:
                continue
            try:
                us.send(msg)
            except:
                continue

        # print(msg)
        # user_socket.send(msg)


import asyncio
import websockets
from utils.redisconn import r


# 检测客户端权限，用户名密码通过才能退出循环
async def check_permit(websocket):
    while True:
        recv_str = await websocket.recv()
        cred_dict = recv_str.split(":")
        if cred_dict[0] == "admin" and cred_dict[1] == "123456":
            response_str = "congratulation, you have connect with server\r\nnow, you can do something else"
            await websocket.send(response_str)
            return True
        else:
            response_str = "sorry, the username or password is wrong, please submit again"
            await websocket.send(response_str)


import json

userlist = []


# 接收客户端消息并处理，这里只是简单把客户端发来的返回回去
async def recv_msg(websocket):
    while True:
        recv_text = await websocket.recv()
        userlist.append(recv_text)
        response_text = f"your submit context: {recv_text}"
        mes = r.get_all_hash_params('task2')
        test = ''
        for k, v in mes.items():
            test = test + str(k, encoding='utf8')
        print(test)
        await websocket.send(test)


# async def send_msg(websocket):
#         mes = rs.get_all_hash('task2')
#         test = ''
#         for k,v in mes.items():
#             test =test+str(k,encoding='utf8')
#         print(test)
#         await websocket.send(test)

import time


# 服务器端主逻辑
# websocket和path是该函数被回调时自动传过来的，不需要自己传
async def main_logic(websocket, path):
    # await check_permit(websocket)
    await recv_msg(websocket)


# 把ip换成自己本地的ip
start_server = websockets.serve(main_logic, '127.0.0.1', 5000)
# 如果要给被回调的main_logic传递自定义参数，可使用以下形式
# 一、修改回调形式
# import functools
# start_server = websockets.serve(functools.partial(main_logic, other_param="test_value"), '10.10.6.91', 5678)
# 修改被回调函数定义，增加相应参数
# async def main_logic(websocket, path, other_param)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()


@app.route("/group_p")
def group_p():
    return render_template("group_p.html")


if __name__ == '__main__':
    # app.run()
    http_serv = WSGIServer(("0.0.0.0", 9527), application=app, handler_class=WebSocketHandler)
    http_serv.serve_forever()
